import os
from PySide6.QtWidgets import (
    QMainWindow,
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QPushButton,
    QFrame,
    QCheckBox,
    QGridLayout,
    QSizePolicy,
    QScrollArea,
    QFileDialog,
    QMessageBox,
    QDialog,
    QSlider,
    QButtonGroup,
    QRadioButton,
    QLayout,
    QDialogButtonBox,
)
from PySide6.QtCore import Qt, Signal, QSize, QTimer, QSettings, QPoint, QObject, QEvent
from PySide6.QtGui import QPixmap, QKeySequence, QShortcut, QImage, QColor

from config.settings import (
    APP_NAME,
    UI,
    IMAGE_RECOGNITION,
    MATCHING_METHODS,
    ENABLE_PRINT,
    ENABLE_RESULT_IMAGE,
)
from src.views.widgets.buttons import (
    PrimaryButton,
    WarningButton,
    DangerButton,
    SuccessButton,
    InfoButton,
)
from src.utils.style_manager import StyleManager
from src.utils.resource_helper import get_resource_path  # 导入资源加载函数
import tempfile


class CheckboxEventFilter(QObject):
    """复选框事件过滤器，确保在失去焦点时保持选中状态的外观"""

    def eventFilter(self, obj, event):
        if event.type() == QEvent.FocusOut or event.type() == QEvent.WindowDeactivate:
            # 当失去焦点时，如果是选中状态，强制更新
            if obj.isChecked():
                obj.update()
        return False


class MainWindowView(QMainWindow):
    """主窗口视图类，遵循MVC架构"""

    # 定义信号
    capture_screen_signal = Signal()
    start_recognition_signal = Signal()
    stop_recognition_signal = Signal()
    clear_results_signal = Signal()
    save_results_signal = Signal()
    show_settings_signal = Signal()
    change_match_method_signal = Signal(str)
    change_threshold_signal = Signal(float)
    change_click_mode_signal = Signal(bool)
    template_checkbox_toggled_signal = Signal(str, str, bool)
    change_print_mode_signal = Signal(bool)  # 新增打印模式变更信号
    change_result_image_mode_signal = Signal(bool)  # 结果图生成模式变更信号

    def __init__(self):
        super().__init__()
        self.setWindowTitle(APP_NAME)
        self.setMinimumSize(UI["default_width"], UI["default_height"])

        # 主题设置
        self.is_dark_theme = True  # 默认使用深色主题

        # 创建中心部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.main_layout = QVBoxLayout(self.central_widget)
        self.main_layout.setSpacing(15)  # 增加布局间距
        self.main_layout.setContentsMargins(15, 15, 15, 15)  # 增加边距

        # 模板复选框
        self.checkboxes = []
        self.template_frames = []  # 所有模板框架

        # 匹配方法设置
        self.current_match_method = IMAGE_RECOGNITION[
            "default_method"
        ]  # 使用配置中的默认匹配方法
        self.enable_print = ENABLE_PRINT  # 使用配置中的默认值
        self.enable_result_image = ENABLE_RESULT_IMAGE  # 使用配置中的默认值

        # 事件过滤器列表（防止垃圾回收）
        self.event_filters = []

        # 临时文件目录
        self.temp_dir = os.path.join(tempfile.gettempdir(), "PySide6x")
        os.makedirs(self.temp_dir, exist_ok=True)

        # 创建控件，然后再应用主题，确保所有控件都已就绪
        self._setup_ui()
        self._setup_shortcuts()

        # 应用当前主题
        self.apply_theme()
        self.refresh_ui_styles()

        # 创建状态栏更新定时器
        self._status_timer = QTimer()
        self._status_timer.setSingleShot(True)
        self._status_timer.timeout.connect(self._clear_status)

        # 状态栏
        self.statusBar().showMessage("准备就绪")

    def apply_theme(self):
        """应用当前选择的主题"""
        if self.is_dark_theme:
            # 深色主题
            self.setStyleSheet(
                """
                QMainWindow, QDialog {
                    background-color: #1E1E1E;
                    color: #E0E0E0;
                }
                QLabel {
                    color: #E0E0E0;
                }
                QScrollArea {
                    border: none;
                    background-color: transparent;
                }
                QPushButton {
                    background-color: #2D2D30;
                    color: #E0E0E0;
                    border: 1px solid #3F3F46;
                    border-radius: 4px;
                    padding: 5px 10px;
                }
                QPushButton:hover {
                    background-color: #3E3E42;
                    border: 1px solid #007ACC;
                }
                QPushButton:pressed {
                    background-color: #007ACC;
                }
                QFrame {
                    background-color: #252526;
                    border: 1px solid #3F3F46;
                    border-radius: 5px;
                }
                QLineEdit, QTextEdit {
                    background-color: #2D2D30;
                    color: #E0E0E0;
                    border: 1px solid #3F3F46;
                    border-radius: 3px;
                    padding: 2px;
                }
                QCheckBox {
                    color: #E0E0E0;
                }
                QCheckBox::indicator {
                    width: 18px;
                    height: 18px;
                    border-radius: 3px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #3F3F46;
                    background-color: #2D2D30;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #007ACC;
                    background-color: #007ACC;
                }
                QRadioButton {
                    color: #E0E0E0;
                }
                QRadioButton::indicator {
                    width: 18px;
                    height: 18px;
                    border-radius: 9px;
                }
                QRadioButton::indicator:unchecked {
                    border: 1px solid #3F3F46;
                    background-color: #2D2D30;
                }
                QRadioButton::indicator:checked {
                    border: 1px solid #007ACC;
                    background-color: #007ACC;
                }
                QComboBox {
                    background-color: #2D2D30;
                    color: #E0E0E0;
                    border: 1px solid #3F3F46;
                    border-radius: 3px;
                    padding: 1px 18px 1px 3px;
                }
                QComboBox::drop-down {
                    subcontrol-origin: padding;
                    subcontrol-position: top right;
                    width: 20px;
                    border-left: 1px solid #3F3F46;
                }
                QComboBox:on {
                    background-color: #3E3E42;
                }
                QComboBox QAbstractItemView {
                    background-color: #2D2D30;
                    color: #E0E0E0;
                    border: 1px solid #3F3F46;
                    selection-background-color: #007ACC;
                }
                QScrollBar:vertical {
                    background-color: #2D2D30;
                    width: 14px;
                    margin: 15px 0 15px 0;
                    border: 1px solid #3F3F46;
                }
                QScrollBar::handle:vertical {
                    background-color: #3E3E42;
                    min-height: 20px;
                    border-radius: 4px;
                }
                QScrollBar::handle:vertical:hover {
                    background-color: #007ACC;
                }
                QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                    border: none;
                    background: none;
                    height: 14px;
                }
                QScrollBar:horizontal {
                    background-color: #2D2D30;
                    height: 14px;
                    margin: 0 15px 0 15px;
                    border: 1px solid #3F3F46;
                }
                QScrollBar::handle:horizontal {
                    background-color: #3E3E42;
                    min-width: 20px;
                    border-radius: 4px;
                }
                QScrollBar::handle:horizontal:hover {
                    background-color: #007ACC;
                }
                QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
                    border: none;
                    background: none;
                    width: 14px;
                }
            """
            )
            self.statusBar().setStyleSheet("color: #E0E0E0; background-color: #1E1E1E;")
        else:
            # 浅色主题
            self.setStyleSheet(
                """
                QMainWindow, QDialog {
                    background-color: #F5F7FA;
                    color: #424242;
                }
                QLabel {
                    color: #424242;
                }
                QScrollArea {
                    border: none;
                    background-color: transparent;
                }
                QPushButton {
                    background-color: #FFFFFF;
                    color: #424242;
                    border: 1px solid #BDBDBD;
                    border-radius: 4px;
                    padding: 5px 10px;
                }
                QPushButton:hover {
                    background-color: #F5F5F5;
                    border: 1px solid #2196F3;
                }
                QPushButton:pressed {
                    background-color: #E0E0E0;
                }
                QFrame {
                    background-color: #FFFFFF;
                    border: 1px solid #E0E0E0;
                    border-radius: 5px;
                }
                QLineEdit, QTextEdit {
                    background-color: #FFFFFF;
                    color: #424242;
                    border: 1px solid #BDBDBD;
                    border-radius: 3px;
                    padding: 2px;
                }
                QCheckBox {
                    color: #424242;
                }
                QCheckBox::indicator {
                    width: 18px;
                    height: 18px;
                    border-radius: 3px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #BDBDBD;
                    background-color: #FFFFFF;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #2196F3;
                    background-color: #2196F3;
                }
                QRadioButton {
                    color: #424242;
                }
                QRadioButton::indicator {
                    width: 18px;
                    height: 18px;
                    border-radius: 9px;
                }
                QRadioButton::indicator:unchecked {
                    border: 1px solid #BDBDBD;
                    background-color: #FFFFFF;
                }
                QRadioButton::indicator:checked {
                    border: 1px solid #2196F3;
                    background-color: #2196F3;
                }
                QComboBox {
                    background-color: #FFFFFF;
                    color: #424242;
                    border: 1px solid #BDBDBD;
                    border-radius: 3px;
                    padding: 1px 18px 1px 3px;
                }
                QComboBox::drop-down {
                    subcontrol-origin: padding;
                    subcontrol-position: top right;
                    width: 20px;
                    border-left: 1px solid #BDBDBD;
                }
                QComboBox:on {
                    background-color: #F5F5F5;
                }
                QComboBox QAbstractItemView {
                    background-color: #FFFFFF;
                    color: #424242;
                    border: 1px solid #BDBDBD;
                    selection-background-color: #2196F3;
                }
                QScrollBar:vertical {
                    background-color: #F5F5F5;
                    width: 14px;
                    margin: 15px 0 15px 0;
                    border: 1px solid #E0E0E0;
                }
                QScrollBar::handle:vertical {
                    background-color: #BDBDBD;
                    min-height: 20px;
                    border-radius: 4px;
                }
                QScrollBar::handle:vertical:hover {
                    background-color: #2196F3;
                }
                QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                    border: none;
                    background: none;
                    height: 14px;
                }
                QScrollBar:horizontal {
                    background-color: #F5F5F5;
                    height: 14px;
                    margin: 0 15px 0 15px;
                    border: 1px solid #E0E0E0;
                }
                QScrollBar::handle:horizontal {
                    background-color: #BDBDBD;
                    min-width: 20px;
                    border-radius: 4px;
                }
                QScrollBar::handle:horizontal:hover {
                    background-color: #2196F3;
                }
                QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
                    border: none;
                    background: none;
                    width: 14px;
                }
            """
            )
            self.statusBar().setStyleSheet("color: #424242; background-color: #F5F7FA;")

    def _setup_ui(self):
        """设置UI界面"""
        # 设置部分
        self._setup_settings_section()

        # 中间部分
        middle_layout = QHBoxLayout()
        self._setup_left_section(middle_layout)
        self._setup_right_section(middle_layout)
        self.main_layout.addLayout(middle_layout)

        # 底部按钮
        self._setup_bottom_section()

        # 结果显示部分
        self._setup_results_section()

    def _setup_settings_section(self):
        """设置部分UI"""
        settings_layout = QHBoxLayout()
        settings_layout.setContentsMargins(5, 5, 5, 15)  # 增加底部边距

        settings_label = QLabel("设置")
        settings_label.setObjectName("settings_label")  # 添加对象名称
        settings_label.setStyleSheet(
            f"font-size: 16px; font-weight: bold; color: {('#007ACC' if self.is_dark_theme else '#1565C0')};"
        )

        # 初始化时使用当前设置的匹配方法、打印设置和结果图生成设置
        enable_print_text = "打印已启用" if self.enable_print else "打印已禁用"
        enable_result_image_text = "结果图已启用" if self.enable_result_image else "结果图已禁用"
        self.settings_button = QPushButton(f"设置 ({self.current_match_method}) {enable_print_text} {enable_result_image_text}")
        self.settings_button.clicked.connect(self.show_matching_methods)
        # 应用当前主题的样式
        if self.is_dark_theme:
            self.settings_button.setStyleSheet(
                """
                background-color: #2D2D30;
                color: #E0E0E0;
                border: 1px solid #3F3F46;
                border-radius: 5px;
                padding: 6px 10px;
                font-weight: bold;
            """
            )
        else:
            self.settings_button.setStyleSheet(
                """
                background-color: #FFFFFF;
                border: 1px solid #BDBDBD;
                border-radius: 5px;
                padding: 6px 10px;
                color: #424242;
                font-weight: bold;
            """
            )

        # 创建主题切换按钮
        self.theme_switch = QCheckBox("深色主题")
        self.theme_switch.setChecked(self.is_dark_theme)
        self.theme_switch.setStyleSheet(
            """
            QCheckBox {
                font-weight: bold;
                padding: 4px;
                spacing: 5px;
            }
        """
        )
        self.theme_switch.stateChanged.connect(self.toggle_theme)

        settings_layout.addWidget(settings_label)
        settings_layout.addWidget(self.settings_button)
        settings_layout.addStretch()
        settings_layout.addWidget(self.theme_switch)  # 添加到右侧

        # 添加分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        separator.setStyleSheet(
            f"background-color: {('#3F3F46' if self.is_dark_theme else '#E0E0E0')}; margin: 5px 0;"
        )
        separator.setMaximumHeight(1)

        self.main_layout.addLayout(settings_layout)
        self.main_layout.addWidget(separator)

    def _setup_left_section(self, parent_layout):
        """左侧部分UI"""
        left_frame = QFrame()
        left_frame.setObjectName("left_frame")  # 添加对象名称
        left_frame.setFrameStyle(QFrame.StyledPanel)
        # 直接设置样式，不使用StyleManager
        left_frame.setStyleSheet(
            """
            background-color: #252526;
            border: 1px solid #3F3F46;
            border-radius: 5px;
            padding: 12px;
        """
        )
        # 设置固定宽度，确保截图后宽度不变
        left_frame.setFixedWidth(350)
        left_layout = QVBoxLayout(left_frame)
        left_layout.setSpacing(5)  # 减小控件间距
        left_layout.setContentsMargins(0, 5, 0, 5)  # 移除左右边距

        # 标题
        title_layout = QHBoxLayout()
        left_title = QLabel("待识别图片")
        left_title.setObjectName("left_title")  # 添加对象名称
        # 设置自适应大小策略
        left_title.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
        left_title.setFixedWidth(320)  # 设置与image_preview相同的宽度
        # 合并原有SectionTitle样式和新的padding设置
        left_title.setStyleSheet(
            """
            font-size: 18px;
            font-weight: bold;
            color: #007ACC;
            padding-left: 5px;
            padding-top: 10px;
            padding-bottom: 10px;
            border-left: 4px solid #007ACC;
        """
        )
        title_layout.addStretch()
        title_layout.addWidget(left_title)
        title_layout.addStretch()
        left_layout.addLayout(title_layout)

        # 截图按钮
        button_layout = QHBoxLayout()
        self.region_screenshot_btn = PrimaryButton("选择截图区域")
        self.region_screenshot_btn.setFixedWidth(320)  # 设置与image_preview相同的宽度
        self.region_screenshot_btn.setStyleSheet(
            """
            background-color: #0E639C;
            color: #FFFFFF;
            border: none;
            border-radius: 4px;
            padding: 6px;
        """
        )
        self.region_screenshot_btn.clicked.connect(
            lambda: self.capture_screen_signal.emit()
        )
        button_layout.addStretch()
        button_layout.addWidget(self.region_screenshot_btn)
        button_layout.addStretch()
        left_layout.addLayout(button_layout, 0)

        # 图片预览
        preview_layout = QHBoxLayout()
        self.image_preview = QLabel()
        # 恢复拉伸显示
        self.image_preview.setScaledContents(True)
        self.image_preview.setFrameStyle(QFrame.StyledPanel)
        # 保持固定宽度和高度
        self.image_preview.setFixedSize(320, 180)
        self.image_preview.setAlignment(Qt.AlignCenter)
        self.image_preview.setText("点击选择截图区域预览图片")
        self.image_preview.setStyleSheet(
            """
            background-color: #2D2D30;
            border: 1px solid #3F3F46;
            border-radius: 8px;
            padding: 5px;
            color: #9CDCFE;
        """
        )
        preview_layout.addStretch()
        preview_layout.addWidget(self.image_preview)
        preview_layout.addStretch()
        left_layout.addLayout(preview_layout)

        # 图片信息
        info_layout = QHBoxLayout()
        self.image_info = QLabel("图片信息:\n尺寸: \n路径: \n大小: ")
        # 设置垂直对齐方式为顶部对齐
        self.image_info.setAlignment(Qt.AlignTop)
        # 设置与image_preview相同的宽度
        self.image_info.setFixedWidth(320)
        # 启用自动换行
        self.image_info.setWordWrap(True)
        self.image_info.setStyleSheet("color: #DCDCAA;")
        info_layout.addStretch()
        info_layout.addWidget(self.image_info)
        info_layout.addStretch()
        left_layout.addLayout(info_layout)

        parent_layout.addWidget(left_frame, 1)

    def _setup_right_section(self, parent_layout):
        """右侧部分UI"""
        right_frame = QFrame()
        right_frame.setObjectName("right_frame")  # 添加对象名称
        right_frame.setFrameStyle(QFrame.StyledPanel)
        # 直接设置样式，不使用StyleManager
        right_frame.setStyleSheet(
            """
            background-color: #252526;
            border: 1px solid #3F3F46;
            border-radius: 5px;
            padding: 12px;
        """
        )
        right_layout = QVBoxLayout(right_frame)
        right_layout.setSpacing(5)  # 减小控件间距
        right_layout.setContentsMargins(0, 5, 0, 5)  # 移除左右边距

        # 标题
        right_title = QLabel("待识别图片列表")
        right_title.setObjectName("right_title")  # 添加对象名称
        right_title.setWordWrap(True)
        right_title.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        right_title.setStyleSheet(
            """
            font-size: 18px;
            font-weight: bold;
            color: #007ACC;
            margin-bottom: 12px;
            padding-left: 5px;
            border-left: 4px solid #007ACC;
        """
        )
        right_layout.addWidget(right_title)

        # 创建网格布局
        grid_layout = QGridLayout()
        grid_layout.setSpacing(2)

        # 创建示例图片和按钮
        self.create_sample_grid(grid_layout)

        # 添加滚动区域
        scroll_widget = QWidget()
        scroll_widget.setLayout(grid_layout)
        scroll_widget.setStyleSheet("background-color: transparent;")
        right_layout.addWidget(scroll_widget, 1)

        parent_layout.addWidget(right_frame, 2)

    def create_sample_grid(self, grid_layout):
        """创建示例模板网格"""
        sample_images = [
            ("assets/images/gold.png", "金"),
            ("assets/images/wood.png", "木"),
            ("assets/images/power.png", "力量"),
            ("assets/images/belt.png", "腰带"),
            ("assets/images/glove.png", "拳套"),
            ("assets/images/ice.png", "爆伤"),
            ("assets/images/mana.png", "回蓝"),
        ]

        # 创建并设置复选框样式 - 使用深色主题样式
        checkbox_style = """
            QCheckBox {
                font-weight: bold;
                padding: 4px;
                color: #E0E0E0;
                spacing: 8px;
            }
            QCheckBox::indicator {
                width: 22px;
                height: 22px;
                border-radius: 5px;
            }
            QCheckBox::indicator:checked {
                background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                    stop:0 #007ACC, stop:1 #005B9C);
                border: 2px solid #007ACC;
                border-radius: 5px;
            }
            QCheckBox::indicator:unchecked {
                background-color: #2D2D30;
                border: 2px solid #3F3F46;
                border-radius: 5px;
            }
            QCheckBox::indicator:hover {
                border: 2px solid #007ACC;
                background-color: rgba(0, 122, 204, 0.2);
            }
            QCheckBox::indicator:disabled:checked {
                background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                    stop:0 #3E3E42, stop:1 #4E4E54);
                border: 2px solid #3F3F46;
                border-radius: 5px;
            }
            QCheckBox::indicator:disabled:unchecked {
                background-color: #2D2D30;
                border: 2px solid #3F3F46;
                border-radius: 5px;
            }
        """

        # 设置深色主题样式
        frame_style = """
            background-color: #252526;
            border: 1px solid #3F3F46;
            border-radius: 5px;
            padding: 8px;
        """

        for col, (img_path, label) in enumerate(sample_images):
            # 创建容器，但不应用阴影
            frame = QFrame()
            frame.setFrameStyle(QFrame.StyledPanel)
            frame.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
            frame.setStyleSheet(frame_style)

            # 将框架添加到模板框架列表中
            self.template_frames.append(frame)

            frame_layout = QVBoxLayout(frame)
            frame_layout.setSpacing(5)
            frame_layout.setContentsMargins(5, 5, 5, 5)

            # 类别标签
            category_label = QLabel(label)
            category_label.setAlignment(Qt.AlignLeft)
            category_label.setWordWrap(True)
            category_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
            category_label.setStyleSheet("color: #CE9178;")
            frame_layout.addWidget(category_label)

            # 图片标签
            img_label = QLabel()
            
            # 使用resource_helper加载图片
            resource_path = get_resource_path(img_path)
            if os.path.exists(resource_path):
                pixmap = QPixmap(resource_path)
            else:
                pixmap = QPixmap(100, 100)
                pixmap.fill(Qt.darkGray)
            
            img_label.setPixmap(pixmap)
            img_label.setAlignment(Qt.AlignLeft)
            frame_layout.addWidget(img_label)

            # 启用复选框
            use_checkbox = QCheckBox("启用")
            use_checkbox.setProperty("target_image", img_path)  # 保留原始路径作为属性
            use_checkbox.setProperty("target_label", label)
            use_checkbox.setProperty("is_programmatic", False)
            use_checkbox.setStyleSheet(checkbox_style)
            use_checkbox.setTristate(False)  # 禁用三态

            # 添加额外方法来强制更新选中状态
            def checkbox_update_state():
                checked = use_checkbox.isChecked()
                use_checkbox.update()
                return checked

            use_checkbox.updateState = checkbox_update_state

            # 事件过滤器
            event_filter = CheckboxEventFilter()
            use_checkbox.installEventFilter(event_filter)
            self.event_filters.append(event_filter)  # 保持引用，防止被垃圾回收

            # 连接信号
            use_checkbox.clicked.connect(
                lambda checked, cb=use_checkbox, lbl=label: self.on_checkbox_clicked(
                    checked, cb, lbl
                )
            )
            frame_layout.addWidget(use_checkbox)

            # 尺寸信息
            size_label = QLabel(f"尺寸: {pixmap.width()}x{pixmap.height()}")
            size_label.setAlignment(Qt.AlignLeft)
            size_label.setStyleSheet("color: #4EC9B0;")
            frame_layout.addWidget(size_label)

            # 参数设置按钮
            params_btn = WarningButton("参数设置")
            params_btn.setStyleSheet(
                """
                background-color: #705800;
                color: #FFFFFF;
                border: none;
                border-radius: 3px;
                padding: 5px;
            """
            )
            frame_layout.addWidget(params_btn)

            grid_layout.addWidget(frame, 0, col)

            # 将复选框添加到列表中
            self.checkboxes.append(use_checkbox)

    def on_checkbox_clicked(self, checked, checkbox, label):
        """处理复选框点击事件"""
        if not checkbox.property("is_programmatic"):
            # 获取模板信息
            img_path = checkbox.property("target_image")
            template_label = checkbox.property("target_label")

            # 强制更新复选框状态
            checked = checkbox.updateState()

            # 获取资源的实际路径
            resource_path = get_resource_path(img_path)
            
            # 发送信号到控制器，同时发送原始路径和实际资源路径
            self.template_checkbox_toggled_signal.emit(
                resource_path, template_label, checked
            )

            # 更新状态栏
            self.update_selected_templates_status()

    def _setup_bottom_section(self):
        """底部按钮区域UI"""
        # 添加上方分隔线
        top_separator = QFrame()
        top_separator.setObjectName("top_separator")  # 添加对象名称
        top_separator.setFrameShape(QFrame.HLine)
        top_separator.setFrameShadow(QFrame.Sunken)
        top_separator.setStyleSheet(
            f"background-color: {('#3F3F46' if self.is_dark_theme else '#E0E0E0')}; margin: 5px 0;"
        )
        top_separator.setMaximumHeight(1)
        self.main_layout.addWidget(top_separator)

        bottom_layout = QHBoxLayout()
        bottom_layout.setContentsMargins(5, 15, 5, 5)  # 增加顶部边距
        bottom_layout.setSpacing(10)  # 增加按钮间距

        # 开始识别按钮
        self.start_btn = DangerButton("开始识别 (Ctrl+[)")
        self.start_btn.setShortcut("Ctrl+[")  # 添加快捷键Ctrl+[
        self.start_btn.setStyleSheet(
            """
            background-color: #6E1100;
            color: #FFFFFF;
            border: none;
            border-radius: 3px;
            padding: 5px 10px;
        """
        )
        self.start_btn.clicked.connect(lambda: self.start_recognition_signal.emit())
        bottom_layout.addWidget(self.start_btn)

        # 停止识别按钮
        self.stop_btn = InfoButton("停止识别 (Ctrl+])")
        self.stop_btn.setShortcut("Ctrl+]")  # 添加快捷键Ctrl+]
        self.stop_btn.setStyleSheet(
            """
            background-color: #1F4E79;
            color: #FFFFFF;
            border: none;
            border-radius: 3px;
            padding: 5px 10px;
        """
        )
        self.stop_btn.clicked.connect(lambda: self.stop_recognition_signal.emit())
        bottom_layout.addWidget(self.stop_btn)

        # 清空按钮
        self.clear_btn = WarningButton("清空客户端")
        self.clear_btn.setStyleSheet(
            """
            background-color: #705800;
            color: #FFFFFF;
            border: none;
            border-radius: 3px;
            padding: 5px 10px;
        """
        )
        self.clear_btn.clicked.connect(lambda: self.clear_results_signal.emit())
        bottom_layout.addWidget(self.clear_btn)

        # 保存按钮
        self.save_btn = PrimaryButton("保存标准点")
        self.save_btn.setEnabled(False)
        self.save_btn.setStyleSheet(
            """
            background-color: #0E639C;
            color: #FFFFFF;
            border: none;
            border-radius: 3px;
            padding: 5px 10px;
        """
        )
        self.save_btn.clicked.connect(lambda: self.save_results_signal.emit())
        bottom_layout.addWidget(self.save_btn)

        # 设置按钮
        self.settings_btn = SuccessButton("设置回调")
        self.settings_btn.setStyleSheet(
            """
            background-color: #347434;
            color: #FFFFFF;
            border: none;
            border-radius: 3px;
            padding: 5px 10px;
        """
        )
        self.settings_btn.clicked.connect(lambda: self.show_settings_signal.emit())
        bottom_layout.addWidget(self.settings_btn)

        self.main_layout.addLayout(bottom_layout)

    def _setup_results_section(self):
        """结果显示部分UI"""
        results_layout = QVBoxLayout()

        # 标题
        results_title = QLabel("识别结果")
        results_title.setObjectName("results_title")  # 添加对象名称
        results_title.setStyleSheet(
            """
            font-size: 18px;
            font-weight: bold;
            color: #007ACC;
            margin-bottom: 12px;
            padding-left: 5px;
            border-left: 4px solid #007ACC;
        """
        )
        results_layout.addWidget(results_title)

        # 结果显示区域
        results_display = QHBoxLayout()

        # 左侧文本结果
        left_result = QFrame()
        left_result.setObjectName("left_result_frame")  # 添加对象名称
        left_result.setFrameStyle(QFrame.StyledPanel)
        left_result.setStyleSheet(
            """
            background-color: #252526;
            border: 1px solid #3F3F46;
            border-radius: 5px;
        """
        )
        left_result_layout = QVBoxLayout(left_result)
        self.left_result_label = QLabel('请选择截图区域并点击"开始识别"按钮')
        self.left_result_label.setObjectName("left_result_label")  # 添加对象名称
        self.left_result_label.setAlignment(Qt.AlignCenter)
        self.left_result_label.setStyleSheet("color: #DCDCAA;")
        left_result_layout.addWidget(self.left_result_label)

        # 右侧图像结果
        right_result = QFrame()
        right_result.setObjectName("right_result_frame")  # 添加对象名称
        right_result.setFrameStyle(QFrame.StyledPanel)
        right_result.setStyleSheet(
            """
            background-color: #252526;
            border: 1px solid #3F3F46;
            border-radius: 5px;
            """
        )
        right_result_layout = QVBoxLayout(right_result)
        self.right_result_label = QLabel("识别结果图像将在这里显示")
        self.right_result_label.setObjectName("right_result_label")  # 添加对象名称
        self.right_result_label.setAlignment(Qt.AlignCenter)
        # 恢复拉伸显示
        self.right_result_label.setScaledContents(True)
        self.right_result_label.setFixedSize(320, 180)
        self.right_result_label.setStyleSheet(
            """
            background-color: #2D2D30;
            border: 1px solid #3F3F46;
            border-radius: 8px;
            padding: 5px;
            color: #9CDCFE;
            """
        )
        self.right_result_label.setMouseTracking(True)
        right_result_layout.addWidget(self.right_result_label)

        results_display.addWidget(left_result)
        results_display.addWidget(right_result)
        results_layout.addLayout(results_display)

        self.main_layout.addLayout(results_layout)

    def _setup_shortcuts(self):
        """设置快捷键"""
        # 此处不需要重复定义快捷键，已在按钮上直接设置了快捷键
        pass

    def update_image_preview(self, pixmap: QPixmap, info_text: str):
        """更新图片预览"""
        if not pixmap.isNull():
            # 直接设置图像，让setScaledContents来拉伸
            self.image_preview.setPixmap(pixmap)
        else:
            self.image_preview.clear()
            self.image_preview.setText("点击选择截图区域预览图片")

        # 处理文本格式，确保路径显示在新行且长路径使用省略号
        # 查找路径部分
        path_index = info_text.find("路径: ")
        if path_index != -1:
            # 提取路径信息
            before_path = info_text[:path_index]  # 不包含"路径: "
            
            size_index = info_text.find("\n大小: ")
            if size_index != -1:
                # 提取路径和大小部分
                path_part = info_text[path_index:size_index]
                path_text = path_part.replace("路径: ", "").strip()
                size_part = info_text[size_index:]
                
                # 处理长路径，使用省略号
                MAX_PATH_LENGTH = 30
                if len(path_text) > MAX_PATH_LENGTH:
                    # 保留路径的开始和结尾部分，中间用省略号代替
                    half_length = (MAX_PATH_LENGTH - 3) // 2
                    path_text = path_text[:half_length] + "..." + path_text[-half_length:]
                
                # 重新组织文本，确保路径单独在一行
                info_text = f"{before_path}路径: {path_text}{size_part}"

        self.image_info.setText(info_text)

    def update_recognition_results(self, text_result: str, image_result: QPixmap):
        """更新识别结果"""
        self.left_result_label.setText(text_result)
        if self.left_result_label.alignment() != (Qt.AlignLeft | Qt.AlignTop):
            self.left_result_label.setAlignment(Qt.AlignLeft | Qt.AlignTop)

        if image_result and not image_result.isNull():
            # 直接设置图像，让setScaledContents来拉伸
            self.right_result_label.setPixmap(image_result)
            # 清除文本，显示图像
            self.right_result_label.setText("")
        else:
            self.right_result_label.clear()
            self.right_result_label.setText("未找到匹配结果")
            self.right_result_label.setAlignment(Qt.AlignCenter)

    def show_status_message(self, message: str, timeout: int = 0):
        """显示状态栏消息

        Args:
            message: 消息内容
            timeout: 超时时间(毫秒)，0表示不超时
        """
        self.statusBar().showMessage(message)

        if timeout > 0:
            self._status_timer.start(timeout)

    def _clear_status(self):
        """清除状态栏消息"""
        self.statusBar().clearMessage()

    def update_method_button_text(self, method: str, enable_print: bool, enable_result_image: bool = None):
        """更新方法按钮文本"""
        # 如果没有提供结果图生成设置，使用当前值
        if enable_result_image is None:
            enable_result_image = self.enable_result_image
            
        enable_print_text = "打印已启用" if enable_print else "打印已禁用"
        enable_result_image_text = "结果图已启用" if enable_result_image else "结果图已禁用"
        self.settings_button.setText(f"设置 ({method}) {enable_print_text} {enable_result_image_text}")

    def show_matching_methods(self):
        """显示匹配方法选择对话框"""
        dialog = QDialog(self)
        dialog.setWindowTitle("选择匹配方法")
        dialog.setMinimumWidth(400)
        dialog.setModal(True)

        # 根据当前主题设置样式
        if self.is_dark_theme:
            dialog.setStyleSheet(
                """
                QDialog {
                    background-color: #1E1E1E;
                    color: #E0E0E0;
                }
                QLabel {
                    color: #E0E0E0;
                }
                QPushButton {
                    background-color: #2D2D30;
                    color: #E0E0E0;
                    border: 1px solid #3F3F46;
                    border-radius: 4px;
                    padding: 5px 10px;
                }
                QPushButton:hover {
                    background-color: #3E3E42;
                    border: 1px solid #007ACC;
                }
                QRadioButton {
                    color: #E0E0E0;
                }
                QRadioButton::indicator {
                    width: 18px;
                    height: 18px;
                    border-radius: 9px;
                }
                QRadioButton::indicator:unchecked {
                    border: 1px solid #3F3F46;
                    background-color: #2D2D30;
                }
                QRadioButton::indicator:checked {
                    border: 1px solid #007ACC;
                    background-color: #007ACC;
                }
                QCheckBox {
                    color: #E0E0E0;
                }
                QCheckBox::indicator {
                    width: 18px;
                    height: 18px;
                    border-radius: 3px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #3F3F46;
                    background-color: #2D2D30;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #007ACC;
                    background-color: #007ACC;
                }
            """
            )
        else:
            dialog.setStyleSheet(
                """
                QDialog {
                    background-color: #F5F7FA;
                    color: #424242;
                }
                QLabel {
                    color: #424242;
                }
                QPushButton {
                    background-color: #FFFFFF;
                    color: #424242;
                    border: 1px solid #BDBDBD;
                    border-radius: 4px;
                    padding: 5px 10px;
                }
                QPushButton:hover {
                    background-color: #F5F5F5;
                    border: 1px solid #2196F3;
                }
                QRadioButton {
                    color: #424242;
                }
                QRadioButton::indicator {
                    width: 18px;
                    height: 18px;
                    border-radius: 9px;
                }
                QRadioButton::indicator:unchecked {
                    border: 1px solid #BDBDBD;
                    background-color: #FFFFFF;
                }
                QRadioButton::indicator:checked {
                    border: 1px solid #2196F3;
                    background-color: #2196F3;
                }
                QCheckBox {
                    color: #424242;
                }
                QCheckBox::indicator {
                    width: 18px;
                    height: 18px;
                    border-radius: 3px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #BDBDBD;
                    background-color: #FFFFFF;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #2196F3;
                    background-color: #2196F3;
                }
            """
            )

        layout = QVBoxLayout(dialog)
        layout.setSpacing(10)

        # 标题
        title_label = QLabel("选择匹配方法:")
        title_label.setStyleSheet("font-weight: bold; font-size: 14px;")
        layout.addWidget(title_label)

        # 创建按钮组
        method_group = QButtonGroup(dialog)
        method_group.setExclusive(True)  # 确保只能选择一个匹配方法

        # 添加匹配方法选项
        for i, method in enumerate(MATCHING_METHODS):
            radio_btn = QRadioButton(f"{method}")
            method_group.addButton(radio_btn, i)
            # 如果是当前选中的方法，则选中相应的单选按钮
            # 从settings_button的文本中提取当前方法
            button_text = self.settings_button.text()
            if "(" in button_text and ")" in button_text:
                current_method = button_text.split("(")[1].split(")")[0]
                if method == current_method:
                    radio_btn.setChecked(True)
            elif method == self.current_match_method:
                radio_btn.setChecked(True)
            layout.addWidget(radio_btn)

        # 添加分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        separator.setStyleSheet(
            f"background-color: {('#3F3F46' if self.is_dark_theme else '#E0E0E0')}; margin: 10px 0;"
        )
        separator.setMaximumHeight(1)
        layout.addWidget(separator)

        # 添加打印选项组标题
        options_title = QLabel("其他设置:")
        options_title.setStyleSheet("font-weight: bold; font-size: 14px;")
        layout.addWidget(options_title)

        # 添加打印选项和结果图生成选项 - 放入单独的按钮组
        options_group = QButtonGroup(dialog)
        options_group.setExclusive(False)  # 非排他性，允许复选框独立切换

        print_checkbox = QCheckBox("启用打印匹配结果")
        print_checkbox.setChecked(self.enable_print)
        options_group.addButton(print_checkbox, 0)
        
        result_image_checkbox = QCheckBox("生成识别后的结果图")
        result_image_checkbox.setChecked(self.enable_result_image)
        options_group.addButton(result_image_checkbox, 1)

        layout.addWidget(print_checkbox)
        layout.addWidget(result_image_checkbox)

        # 按钮区域 - 使用QDialogButtonBox
        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, 
            Qt.Horizontal, 
            dialog
        )
        
        # 设置确定按钮样式
        ok_btn = button_box.button(QDialogButtonBox.Ok)
        cancel_btn = button_box.button(QDialogButtonBox.Cancel)
        
        if self.is_dark_theme:
            ok_btn.setStyleSheet("background-color: #0E639C; color: #FFFFFF;")
        else:
            ok_btn.setStyleSheet("background-color: #2196F3; color: #FFFFFF;")
            
        # 重命名按钮
        ok_btn.setText("确定")
        cancel_btn.setText("取消")

        layout.addWidget(button_box)

        # 连接信号
        button_box.accepted.connect(dialog.accept)
        button_box.rejected.connect(dialog.reject)

        # 显示对话框
        if dialog.exec() == QDialog.Accepted:
            changed = False
            
            # 处理匹配方法的变更
            selected_id = method_group.checkedId()
            if selected_id != -1:
                # 获取选中的匹配方法名称
                methods_list = list(MATCHING_METHODS.keys())
                selected_method = methods_list[selected_id]
                # 检查是否发生变化
                if selected_method != self.current_match_method:
                    # 更新实例变量
                    self.current_match_method = selected_method
                    # 发送信号到控制器
                    self.change_match_method_signal.emit(selected_method)
                    changed = True
            
            # 单独处理打印选项的变更
            enable_print = print_checkbox.isChecked()
            if enable_print != self.enable_print:
                # 更新实例变量
                self.enable_print = enable_print
                # 发送打印选项更改信号
                self.change_print_mode_signal.emit(enable_print)
                changed = True
                
            # 单独处理结果图生成选项的变更
            enable_result_image = result_image_checkbox.isChecked()
            if enable_result_image != self.enable_result_image:
                # 更新实例变量
                self.enable_result_image = enable_result_image
                # 发送结果图生成选项更改信号
                self.change_result_image_mode_signal.emit(enable_result_image)
                changed = True
            
            # 无论是否有变更，都更新按钮文本以确保显示正确
            self.update_method_button_text(self.current_match_method, self.enable_print, self.enable_result_image)
            
            # 只有当有变更时才显示状态信息
            if changed:
                # 在状态栏显示信息
                print_status = "启用" if self.enable_print else "禁用"
                result_image_status = "启用" if self.enable_result_image else "禁用"
                self.show_status_message(
                    f"设置已更新: 匹配方法 {self.current_match_method}, 打印 {print_status}, 结果图 {result_image_status}", 
                    3000
                )

    def update_selected_templates_status(self):
        """更新状态栏显示已选中的模板数量"""
        selected_count = sum(1 for cb in self.checkboxes if cb.isChecked())
        if selected_count > 0:
            template_names = [
                cb.property("target_label") for cb in self.checkboxes if cb.isChecked()
            ]
            template_text = ", ".join(template_names)
            self.show_status_message(f"已选中{selected_count}个模板: {template_text}")
        else:
            self.show_status_message("未选中任何模板")

    def show_message_box(self, title, message, icon=QMessageBox.Information):
        """显示消息框"""
        msg_box = QMessageBox(self)
        msg_box.setWindowTitle(title)
        msg_box.setText(message)
        msg_box.setIcon(icon)
        return msg_box.exec()

    def get_save_file_path(self, title, filter_str):
        """获取保存文件路径"""
        return QFileDialog.getSaveFileName(self, title, "", filter_str)[0]

    def get_checkboxes(self):
        """获取所有复选框"""
        return self.checkboxes

    def get_checked_templates(self):
        """获取所有选中的模板"""
        return [
            (cb.property("target_image"), cb.property("target_label"))
            for cb in self.checkboxes
            if cb.isChecked()
        ]

    def toggle_theme(self, state):
        """切换主题"""
        # 直接使用checkbox的isChecked()方法来获取当前选择状态
        # 注意：state参数在这里可能会有问题，因为Qt的信号机制
        self.is_dark_theme = self.theme_switch.isChecked()

        # 更新状态栏信息
        theme_name = "深色" if self.is_dark_theme else "浅色"
        self.show_status_message(f"已切换到{theme_name}主题", 2000)

        # 应用主题
        self.apply_theme()
        self.refresh_ui_styles()

    def refresh_ui_styles(self):
        """刷新UI样式，在主题切换时调用"""
        # 更新设置部分
        settings_label_color = "#007ACC" if self.is_dark_theme else "#1565C0"

        # 更新设置标签样式
        settings_label = self.findChild(QLabel, "settings_label")
        if settings_label:
            settings_label.setStyleSheet(
                f"font-size: 16px; font-weight: bold; color: {settings_label_color};"
            )

        # 更新主题切换样式
        self.theme_switch.setStyleSheet(
            f"""
            QCheckBox {{
                font-weight: bold;
                padding: 4px;
                color: {('#E0E0E0' if self.is_dark_theme else '#424242')};
                spacing: 5px;
            }}
            QCheckBox::indicator {{
                width: 18px;
                height: 18px;
                border-radius: 3px;
            }}
            QCheckBox::indicator:unchecked {{
                border: 1px solid {('#3F3F46' if self.is_dark_theme else '#BDBDBD')};
                background-color: {('#2D2D30' if self.is_dark_theme else '#FFFFFF')};
            }}
            QCheckBox::indicator:checked {{
                border: 1px solid {('#007ACC' if self.is_dark_theme else '#2196F3')};
                background-color: {('#007ACC' if self.is_dark_theme else '#2196F3')};
            }}
        """
        )

        # 更新设置按钮样式
        if self.is_dark_theme:
            self.settings_button.setStyleSheet(
                """
                background-color: #2D2D30;
                color: #E0E0E0;
                border: 1px solid #3F3F46;
                border-radius: 5px;
                padding: 6px 10px;
                font-weight: bold;
            """
            )
        else:
            self.settings_button.setStyleSheet(
                """
                background-color: #FFFFFF;
                border: 1px solid #BDBDBD;
                border-radius: 5px;
                padding: 6px 10px;
                color: #424242;
                font-weight: bold;
            """
            )

        # 重新应用主题样式
        self.apply_theme()

        # 直接更新主要框架的样式而不使用QLayout
        left_frame = self.findChild(QFrame, "left_frame")
        right_frame = self.findChild(QFrame, "right_frame")

        if left_frame:
            if self.is_dark_theme:
                left_frame.setStyleSheet(
                    """
                    background-color: #252526;
                    border: 1px solid #3F3F46;
                    border-radius: 5px;
                    padding: 12px;
                """
                )
            else:
                left_frame.setStyleSheet(
                    """
                    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, 
                                   stop:0 #FFFFFF, stop:1 #F5F5F5);
                    border-radius: 10px;
                    border: 1px solid #E0E0E0;
                    padding: 12px;
                """
                )

        if right_frame:
            if self.is_dark_theme:
                right_frame.setStyleSheet(
                    """
                    background-color: #252526;
                    border: 1px solid #3F3F46;
                    border-radius: 5px;
                """
                )
            else:
                right_frame.setStyleSheet(
                    """
                    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, 
                                   stop:0 #FFFFFF, stop:1 #F5F5F5);
                    border-radius: 10px;
                    border: 1px solid #E0E0E0;
                    padding: 12px;
                """
                )

        # 更新图片预览区域样式
        if hasattr(self, "image_preview"):
            if self.is_dark_theme:
                self.image_preview.setStyleSheet(
                    """
                    background-color: #2D2D30;
                    border: 1px solid #3F3F46;
                    border-radius: 8px;
                    padding: 5px;
                    color: #9CDCFE;
                """
                )
            else:
                self.image_preview.setStyleSheet(
                    """
                    background-color: #FAFAFA;
                    border: 1px solid #BDBDBD;
                    border-radius: 8px;
                    padding: 5px;
                    color: #424242;
                """
                )

        # 更新左侧和右侧标题样式
        left_title = self.findChild(QLabel, "left_title")
        right_title = self.findChild(QLabel, "right_title")

        if left_title:
            # 标题文字颜色和边框颜色
            title_color = "#007ACC" if self.is_dark_theme else "#1565C0"
            left_title.setStyleSheet(
                f"""
                font-size: 18px;
                font-weight: bold;
                color: {title_color};
                padding-left: 5px;
                padding-top: 10px;
                padding-bottom: 10px;
                border-left: 4px solid {title_color};
            """
            )

        if right_title:
            title_color = "#007ACC" if self.is_dark_theme else "#1565C0"
            right_title.setStyleSheet(
                f"""
                font-size: 18px;
                font-weight: bold;
                color: {title_color};
                margin-bottom: 12px;
                padding-left: 5px;
                border-left: 4px solid {title_color};
            """
            )

        # 更新截图按钮样式
        if hasattr(self, "region_screenshot_btn"):
            if self.is_dark_theme:
                self.region_screenshot_btn.setStyleSheet(
                    """
                    background-color: #0E639C;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 4px;
                    padding: 6px;
                """
                )
            else:
                self.region_screenshot_btn.setStyleSheet(
                    """
                    background-color: #2196F3;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 4px;
                    padding: 6px;
                """
                )

        # 更新图片列表项目样式
        if hasattr(self, "template_frames") and self.template_frames:
            for i, template_frame in enumerate(self.template_frames):
                if self.is_dark_theme:
                    template_frame.setStyleSheet(
                        """
                        background-color: #2D2D30;
                        border: 1px solid #3F3F46;
                        border-radius: 5px;
                        padding: 5px;
                    """
                    )
                else:
                    template_frame.setStyleSheet(
                        """
                        background-color: #FFFFFF;
                        border: 1px solid #E0E0E0;
                        border-radius: 5px;
                        padding: 5px;
                    """
                    )

                # 更新列表中的标签和复选框样式
                for child in template_frame.findChildren(QLabel):
                    if self.is_dark_theme:
                        child.setStyleSheet("color: #E0E0E0;")
                    else:
                        child.setStyleSheet("color: #424242;")

                # 更新参数设置按钮样式
                for btn in template_frame.findChildren(QPushButton):
                    if self.is_dark_theme:
                        btn.setStyleSheet(
                            """
                            background-color: #705800;
                            color: #FFFFFF;
                            border: none;
                            border-radius: 4px;
                            padding: 5px;
                            """
                        )
                    else:
                        btn.setStyleSheet(
                            """
                            background-color: #FF9800;
                            color: #FFFFFF;
                            border: none;
                            border-radius: 4px;
                            padding: 5px;
                            """
                        )

                # 更新复选框样式
                for cb in template_frame.findChildren(QCheckBox):
                    if self.is_dark_theme:
                        cb.setStyleSheet(
                            """
                            QCheckBox {
                                color: #E0E0E0;
                                spacing: 5px;
                            }
                            QCheckBox::indicator {
                                width: 16px;
                                height: 16px;
                                border-radius: 3px;
                            }
                            QCheckBox::indicator:unchecked {
                                border: 1px solid #3F3F46;
                                background-color: #2D2D30;
                            }
                            QCheckBox::indicator:checked {
                                border: 1px solid #007ACC;
                                background-color: #007ACC;
                            }
                        """
                        )
                    else:
                        cb.setStyleSheet(
                            """
                            QCheckBox {
                                color: #424242;
                                spacing: 5px;
                            }
                            QCheckBox::indicator {
                                width: 16px;
                                height: 16px;
                                border-radius: 3px;
                            }
                            QCheckBox::indicator:unchecked {
                                border: 1px solid #BDBDBD;
                                background-color: #FFFFFF;
                            }
                            QCheckBox::indicator:checked {
                                border: 1px solid #2196F3;
                                background-color: #2196F3;
                            }
                        """
                        )

        # 更新底部按钮样式
        if hasattr(self, "start_btn"):
            if self.is_dark_theme:
                self.start_btn.setStyleSheet(
                    """
                    background-color: #6E1100;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )
                self.stop_btn.setStyleSheet(
                    """
                    background-color: #1F4E79;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )
                self.clear_btn.setStyleSheet(
                    """
                    background-color: #705800;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )
                self.save_btn.setStyleSheet(
                    """
                    background-color: #0E639C;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )
                self.settings_btn.setStyleSheet(
                    """
                    background-color: #347434;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )
            else:
                self.start_btn.setStyleSheet(
                    """
                    background-color: #F44336;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )
                self.stop_btn.setStyleSheet(
                    """
                    background-color: #2196F3;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )
                self.clear_btn.setStyleSheet(
                    """
                    background-color: #FF9800;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )
                self.save_btn.setStyleSheet(
                    """
                    background-color: #2196F3;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )
                self.settings_btn.setStyleSheet(
                    """
                    background-color: #4CAF50;
                    color: #FFFFFF;
                    border: none;
                    border-radius: 3px;
                    padding: 5px 10px;
                """
                )

        # 更新标签样式
        if hasattr(self, "left_result_label"):
            if self.is_dark_theme:
                self.left_result_label.setStyleSheet("color: #DCDCAA;")
                self.right_result_label.setStyleSheet(
                    """
                    background-color: #2D2D30;
                    border: 1px solid #3F3F46;
                    border-radius: 8px;
                    padding: 5px;
                    color: #9CDCFE;
                """
                )
            else:
                self.left_result_label.setStyleSheet("color: #795548;")
                self.right_result_label.setStyleSheet(
                    """
                    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                 stop:0 #FAFAFA, stop:1 #F5F5F5);
                    border: 1px solid #BDBDBD;
                    border-radius: 8px;
                    padding: 5px;
                    color: #757575;
                """
                )

        # 更新图片信息标签
        if hasattr(self, "image_info"):
            if self.is_dark_theme:
                self.image_info.setStyleSheet("color: #DCDCAA;")
            else:
                self.image_info.setStyleSheet("color: #795548;")

        # 更新结果区域样式
        results_title = self.findChild(QLabel, "results_title")
        if results_title:
            title_color = "#007ACC" if self.is_dark_theme else "#1565C0"
            results_title.setStyleSheet(
                f"""
                font-size: 18px;
                font-weight: bold;
                color: {title_color};
                margin-bottom: 12px;
                padding-left: 5px;
                border-left: 4px solid {title_color};
            """
            )

        # 更新左侧结果框架
        left_result_frame = self.findChild(QFrame, "left_result_frame")
        if left_result_frame:
            if self.is_dark_theme:
                left_result_frame.setStyleSheet(
                    """
                    background-color: #252526;
                    border: 1px solid #3F3F46;
                    border-radius: 5px;
                """
                )
            else:
                left_result_frame.setStyleSheet(
                    """
                    background-color: #FFFFFF;
                    border: 1px solid #E0E0E0;
                    border-radius: 5px;
                """
                )

        # 更新右侧结果框架
        right_result_frame = self.findChild(QFrame, "right_result_frame")
        if right_result_frame:
            if self.is_dark_theme:
                right_result_frame.setStyleSheet(
                    """
                    background-color: #252526;
                    border: 1px solid #3F3F46;
                    border-radius: 5px;
                """
                )
            else:
                right_result_frame.setStyleSheet(
                    """
                    background-color: #FFFFFF;
                    border: 1px solid #E0E0E0;
                    border-radius: 5px;
                """
                )

        # 更新左侧结果标签
        if hasattr(self, "left_result_label"):
            if self.is_dark_theme:
                self.left_result_label.setStyleSheet("color: #DCDCAA;")
            else:
                self.left_result_label.setStyleSheet("color: #795548;")

        # 更新右侧结果标签
        if hasattr(self, "right_result_label"):
            if self.is_dark_theme:
                self.right_result_label.setStyleSheet(
                    """
                    background-color: #2D2D30;
                    border: 1px solid #3F3F46;
                    border-radius: 8px;
                    padding: 5px;
                    color: #9CDCFE;
                """
                )
            else:
                self.right_result_label.setStyleSheet(
                    """
                    background-color: #FAFAFA;
                    border: 1px solid #BDBDBD;
                    border-radius: 8px;
                    padding: 5px;
                    color: #424242;
                """
                )

        # 更新顶部分隔线样式
        top_separator = self.findChild(QFrame, "top_separator")
        if top_separator:
            top_separator.setStyleSheet(
                f"background-color: {('#3F3F46' if self.is_dark_theme else '#E0E0E0')}; margin: 5px 0;"
            )
